package gro.ecorrdata.edata.util;

import java.util.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;

/**
 * MyUtil by huwhois time 2019/11/12
 */
public class MyUtil {

    /**
     * 将ip地址转为整数 第一值乘256的3次方, 第二个值乘256的平方, ..., 解码时倒过来 
     * 其实也可以第一个乘1, 第二个成256,第三个值乘256的平方, ..., 但这样得到的值无法使用MySQL自带的转换函数
     * 本地::1 解决不了直接舍弃吧
     * @param String ip
     * @return int
     */
    public static Long ipToNum(String ip) {
        long nIp = 0;
        // System.out.println(ip);

        String[] sArray = ip.split("\\.");
        int dd = 256;
        int j = 3;
        for (int i = 0; i < 4; i++) {
            // System.out.println(sArray[i]);
            nIp += Integer.parseInt(sArray[i]) * ((long) Math.pow(dd, j));
            j--;
        }
        // System.out.println(nIp);
        return (Long) nIp;
    }

    /**
     * 将ip地址整数转为字符串
     * 
     * @param String ip
     * @return int
     */
    public static String numToIp(long nIp) {
        String[] str = new String[4];
        // System.out.println(nIp);
        int dd = 256;
        for (int i = 0; i < 4; i++) {
            str[i] = (nIp % dd) + "";
            nIp = (long) Math.floor(nIp / dd);
            // System.out.println(str[i]);
        }
        String ip = "";
        for (int i = 3; i > -1; i--) {
            if (i==0) {
                ip += str[i];
            } else {
                ip += str[i]+".";
            }
        }

        // System.out.println(ip);
        return ip;
    }

    /**
     * java md5加密的方法
     */
    public static String md5(String plainText) {
        // 定义一个字节数组
        byte[] secretBytes = null;
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 对字符串进行加密
            md.update(plainText.getBytes());
            // 获得加密后的数据
            secretBytes = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        // 将加密后的数据转换为16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }

    /**
     * java 获取前段提交的ip
     * 
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static List<Map<String, Object>> makeClassListTree(List<Map<String, Object>> list, String pid){
        List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
        for(Map<String, Object> map : list){
            if(pid.equals(map.get("pid").toString())){
                // System.out.println(map.get("id"));
                map.put("children", addChildClass(map,list));
                treeList.add(map);
            }
        }
        return treeList;
    }
     
    public static List<Object> addChildClass(Map<String, Object> parentMap, List<Map<String, Object>> list){
        List<Object> childList = new ArrayList<Object>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
        parentMap.put("children", childList);
         for (Map<String, Object> childMap : list){
            //如果子节点的pid等于父节点的ID，则说明是父子关系
            if(childMap.get("pid").toString().equals(parentMap.get("id").toString())){
                // 是父子关系，则将其放入子list字面
                childList.add(childMap);
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
                addChildClass(childMap, list);
            }
        }
        // 当遍历完成，返回调用的父节点的所有子节点
        return childList;
    }
}
